package com.hson.demo.base.dao;

import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowMapper;

public class BeanFieldRowMapper<T> implements RowMapper<T> {
	
	private Class<T> beanCls;
	
	public BeanFieldRowMapper(Class<T> beanCls) {
		this.beanCls = beanCls;
	}
	@Override
	public T mapRow(ResultSet rs, int rowNum) throws SQLException {
		try {
			T bean = beanCls.newInstance();
//			if (!rs.next()) {
//				return null;
//			}
			for (Method method : beanCls.getMethods()) {
				
				if (method.getName().startsWith("set") && method.getParameterTypes().length == 1) {
					method.invoke(bean, getValue(rs, 
							StringUtils.uncapitalize(method.getName().substring(3)), method.getParameterTypes()[0]));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}

		return null;
	}
	
	public Object getValue(ResultSet rs, String field, Class<?> returnType) throws Exception {
		if (returnType.equals(Integer.class)) {
			return rs.getInt(field);
		} else if (returnType.equals(String.class)) {
			return rs.getString(field);
		} else if (returnType.equals(Date.class)) {
			Timestamp timestamp = rs.getTimestamp(field);
			if (timestamp == null) {
				return null;
			}
			return new Date(timestamp.getTime());
		} else if (returnType.equals(Long.class)) {
			return rs.getString(field);
		} else if (returnType.equals(Boolean.class)) {
			return rs.getBoolean(field);
		} else {
			return null;
		}
	}
	
}
